package com.taxx.util;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 季度时间工具类
 * 
 * @author taxx
 * @since 2024-01-01
 */
public class QuarterTimeUtil {
    
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    
    /**
     * 获取上一季度的起止时间
     * 
     * @return 包含起止时间的数组，[0]为开始时间，[1]为结束时间
     */
    public static String[] getLastQuarterTime() {
        LocalDate now = LocalDate.now();
        int currentYear = now.getYear();
        int currentMonth = now.getMonthValue();
        
        int lastQuarter = getQuarter(currentMonth) - 1;
        if (lastQuarter == 0) {
            lastQuarter = 4;
            currentYear--;
        }
        
        return getQuarterTime(currentYear, lastQuarter);
    }
    
    /**
     * 获取指定年份和季度的起止时间
     * 
     * @param year 年份
     * @param quarter 季度（1-4）
     * @return 包含起止时间的数组，[0]为开始时间，[1]为结束时间
     */
    public static String[] getQuarterTime(int year, int quarter) {
        if (quarter < 1 || quarter > 4) {
            throw new IllegalArgumentException("季度必须在1-4之间");
        }
        
        int startMonth = (quarter - 1) * 3 + 1;
        int endMonth = quarter * 3;
        
        LocalDate startDate = LocalDate.of(year, startMonth, 1);
        LocalDate endDate = LocalDate.of(year, endMonth, endMonth == 2 ? 28 : 31);
        
        // 如果结束日期超出当月最大天数，调整为当月最后一天
        if (endDate.getMonthValue() != endMonth) {
            endDate = LocalDate.of(year, endMonth, 1).plusMonths(1).minusDays(1);
        }
        
        return new String[]{
            startDate.format(DATE_FORMATTER),
            endDate.format(DATE_FORMATTER)
        };
    }
    
    /**
     * 根据月份获取季度
     * 
     * @param month 月份（1-12）
     * @return 季度（1-4）
     */
    public static int getQuarter(int month) {
        if (month < 1 || month > 12) {
            throw new IllegalArgumentException("月份必须在1-12之间");
        }
        
        if (month <= 3) return 1;
        if (month <= 6) return 2;
        if (month <= 9) return 3;
        return 4;
    }
    
    /**
     * 获取当前季度的起止时间
     * 
     * @return 包含起止时间的数组，[0]为开始时间，[1]为结束时间
     */
    public static String[] getCurrentQuarterTime() {
        LocalDate now = LocalDate.now();
        int currentYear = now.getYear();
        int currentMonth = now.getMonthValue();
        int currentQuarter = getQuarter(currentMonth);
        
        return getQuarterTime(currentYear, currentQuarter);
    }
    
    /**
     * 获取当前日期
     * 
     * @return 当前日期字符串，格式：yyyy-MM-dd
     */
    public static String getCurrentDate() {
        return LocalDate.now().format(DATE_FORMATTER);
    }
}
